package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    public User login(UserLoginDTO userLoginDTO) {

        Map<String, String> map = new HashMap<>();
        map.put("appid", "wx0a3f91494b2674e9");
        map.put("secret", "01f45d6fc85446ff2ff02f10d07b3d89");
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");

        //获取openid
        String s = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");

        //判断有没有登录成功
        if (openid == null) {
            throw new LoginFailedException("登陆失败");
        }

        //是不是新用户
        User user = userMapper.getByOpenid(openid);

        if (user == null) {
            //注册用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())

                    .build();
            userMapper.insert(user);
        }

        return user;
    }
}
